"""
    对 apk_info.yml 文件进行处理
    apk_info.yml 中给三端的默认更新时间 : 1707100000000
"""
import logging
from datetime import datetime, timedelta
import os
import time
from logging.handlers import TimedRotatingFileHandler
from typing import Text

import yaml

APK_INFO_FILE = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'conf', 'apk_info.yml'])
APK_UPDATE_TIME_FILE = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'conf', 'apk_update_time.yml'])
COOKIE_FILE = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'conf', 'cookies.txt'])
APK_FOLDER_FILE = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'conf', 'apk_folders.yml'])
LOG_FILE = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'log', 'log.out'])
CONF_FOLDER = os.sep.join([os.path.dirname(os.path.dirname(__file__)), 'conf'])


def log():
    _t_log = logging.getLogger('auto_teambition')
    _t_log.setLevel(10)

    console = logging.StreamHandler()
    console.setLevel(10)
    _t_log.addHandler(console)

    filehandler = TimedRotatingFileHandler(LOG_FILE, when='W1', backupCount=3, encoding='utf8')
    filehandler.suffix = "%Y-%m-%d_%H-%M-%S.log"
    filehandler.setLevel(20)
    _t_log.addHandler(filehandler)
    return _t_log


class ToolS(object):
    __instance = False

    @classmethod
    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    @property
    def default_time(self):
        """
        如果 teambition 的更新时间在昨天 00:00 之后,
        则进入目录, 下载安装包
        """
        # 以前是从 apk_info.yml 获取 default_updated 作为判断时间,
        # return self.__get_all().get('default_updated')
        return self.yesterday_zero_time
        # TODO: 后续再修改, 将文件夹的时间设置为: 2024-02-05 xx:xx:xx, 但是将 apk 的时间设置为昨天零点

    @property
    def default_date(self):
        _time = self.__get_all().get('default_updated')
        return self.time2date(_time)

    @property
    def collection_url(self):
        return self.__get_all().get('collection_url')

    @property
    def work_url(self):
        return self.__get_all().get('work_url')

    @property
    def project_id(self):
        return self.__get_all().get('project_id')

    @property
    def yl_doctor_updated(self):
        return self.__get_all().get('yl_doctor')

    @property
    def yl_health_updated(self):
        return self.__get_all().get('yl_health')

    @property
    def yl_management_updated(self):
        return self.__get_all().get('yl_management')

    @classmethod
    def __get_all(cls, ):
        with open(APK_INFO_FILE, encoding='utf8') as _f:
            _datas: dict = yaml.safe_load(_f)
            return _datas

    @classmethod
    def get_all(cls, file_name):
        with open(os.sep.join([CONF_FOLDER, f'{file_name}.yml']), encoding='utf8') as _f:
            _datas: dict = yaml.safe_load(_f)
            return _datas

    @staticmethod
    def date2time(date_str: Text):
        """ 2024-02-05 10:26:40 ----> 1707100000000 """
        if date_str.count('T') > 0:
            date_str = f'{date_str[:10]} {date_str[11:19]}'
        try:
            datetime_format = datetime.strptime(str(date_str), "%Y-%m-%d %H:%M:%S")
            timestamp = int(
                time.mktime(datetime_format.timetuple()) * 1000.0
                + datetime_format.microsecond / 1000.0
            )
            return timestamp
        except ValueError as e:
            raise ValueError('日期格式错误, 需要传入得格式为 "%Y-%m-%d %H:%M:%S" ') from e

    @staticmethod
    def time2date(time_num: float = None):
        time_stamp = time.time() if not time_num else time_num
        time_stamp = float(time_num / 1000) if isinstance(time_num, int) else time_stamp
        time_array = time.localtime(time_stamp)
        _date = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
        return _date

    @property
    def params(self):
        _params = {
            # 这里默认值是: 执业版App
            '_parentId': '6531d80256ff22fc166c9ace',
            '_projectId': '6531d7fc2e03b1cdbc524aac',

            'order': 'nameDesc',
            'page': '1',
            'count': '50',
            '_': int(time.time() * 1000),
        }
        return _params

    def get_id(self, terminal):
        """
        从配置文件中获取 id 信息

        doctor_project_id
        doctor_parent_id

        health_project_id
        health_parent_id

        management_project_id
        management_parent_id
        """
        _id = self.__get_all().get(terminal)
        return _id

    @staticmethod
    def write(file_path, _datas):
        with open(file_path, encoding='utf8', mode='w') as _f:
            yaml.safe_dump(_datas, _f, allow_unicode=True)

    @staticmethod
    def cookie_useful(is_useful: bool):
        _file = os.sep.join([CONF_FOLDER, 'cookie_useful.yml'])
        _data = dict(useful=is_useful)
        with open(_file, encoding='utf8', mode='w') as _f:
            yaml.safe_dump(_data, _f, allow_unicode=True)

    @property
    def yesterday_zero_time(self):
        current_time = datetime.now()
        yesterday_time = current_time - timedelta(days=1)
        yesterday_date = yesterday_time.date()
        zero_time = datetime.combine(yesterday_date, datetime.min.time())
        zero_time_use = int(time.mktime(zero_time.timetuple()) * 1000)
        return zero_time_use

    def set_time_yesterday_zero(self):
        _yesterday_zero_time = self.yesterday_zero_time
        with open(APK_UPDATE_TIME_FILE, encoding='utf8', mode='w') as _f:
            _datas = {'update_time': _yesterday_zero_time}
            yaml.safe_dump(_datas)


class RequestParameter:

    @property
    def cookie(self):
        with open(COOKIE_FILE, 'r') as f:
            cookie = f.read()
            return cookie

    @property
    def headers(self):
        headers = {
            # 'authority': 'www.teambition.com',
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'sec-ch-ua': '"Not A(Brand";v="99", "Microsoft Edge";v="121", "Chromium";v="121"', 'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0',
            'x-requested-with': 'XMLHttpRequest', 'cookie': self.cookie}
        return headers

    def set_cookie(self, _cookie):
        """ .. """
        _cookie = 'cna=ukQ6HvkDfg0CAXGMCC6GLqZQ; _bl_uid=81lenre3uILaUyd2L89qmw5ub3am; region=cn; TEAMBITION_SESSIONID=eyJhdXRoVXBkYXRlZCI6MTcwNzE4NjQ2ODk1NCwibG9naW5Gcm9tIjoidGVhbWJpdGlvbiIsInVpZCI6IjY1YzA4ZmV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ug(f'原 cookies ：{self.cookie}')
        log.debug(f'新 cookies ：{_cookie}')

        with open(COOKIE_FILE, 'w') as f:
            f.write(_cookie)
            return _cookie


log = log()
tools = ToolS()
req_param = RequestParameter()

if __name__ == '__main__':
    import time

    # 每 3 秒加载一次 cookie:
    """
    while True:
        time.sleep(3)
        print(RequestParameter().cookie)
    # """

    # 昨天零点:
    """
    print(tools.yesterday_zero_time)
    print(tools.time2date(tools.yesterday_zero_time))

    print(tools.default_time)
    print(tools.time2date(tools.default_time))

    # """

    current_time = time.localtime()
    print(current_time)
    print(current_time.tm_hour)
    print(current_time.tm_min)
    print(current_time.tm_sec)

    # tm_hour 2,3
    # tm_min 55,05
